package com.inforim.cognos.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.inforim.cognos.CognosClient;

public class CognosUtils {

	static Log log = LogFactory.getLog(CognosUtils.class);

	public static String getSearchPath(String path, int scope) {
		if (scope != CognosClient.SCOPE_ONELEVEL
				&& scope != CognosClient.SCOPE_SUBTREE) {
			return path;
		}
		String rPath = path;
		String rOpts = CognosUtils.getSearchOpts(rPath);
		if (!"".equals(rOpts)) {
			rPath = rPath.substring(0, rPath.lastIndexOf(rOpts));
		}
		String ePath = null;
		if (scope == CognosClient.SCOPE_ONELEVEL) {
			ePath = "*";
		} else if (scope == CognosClient.SCOPE_SUBTREE) {
			if(null == ePath) {
				ePath = "";
			}
			ePath += "/*";
		}
		if (null != ePath) {
			if (rPath.endsWith("/*")) {
				rPath = rPath.substring(0, rPath.length() - "/*".length())
						+ "/";
			}
			if (!rPath.endsWith("/")) {
				rPath += "/";
			}
			rPath += ePath;
		}
		if (!"".equals(rOpts)) {
			rPath += rOpts;
		}
		return rPath;
	}

	public static String getSearchOpts(String path) {
		String rPerm = "";
		if (path.matches("^(.*)\\/\\*\\[(.*)\\]$")) {
			rPerm = path.substring(path.lastIndexOf("/*") + "/*".length());
		}
		return rPerm;
	}
}
